package com.anclick.englishword;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBHandler {
	private DBHelper helper;
	private SQLiteDatabase db;
	
	private DBHandler(Context ctx) {
		this.helper =new DBHelper(ctx);
		this.db = helper.getWritableDatabase();
	}
	
	public static DBHandler open(Context ctx) throws SQLException {
		DBHandler handler = new DBHandler(ctx);
		
		return handler;
	}

	public void close() {
		helper.close();
	}
	
	public long insert(String word , String url) {
		ContentValues values =new ContentValues();
		values.put("word" , word);
		values.put("url", url);
		
		return db.insert("words", null, values);
	}
	public boolean delete(long id) {
		return db.delete("words", "_id" + "=" + id, null) > 0 ;
	}
	
	public Cursor select(int id) throws SQLException {
		Cursor cursor = db.query(true, "words", new String[] {"_id" , "word" , "url"} , "_id" + "=" + id, null , null, null,null,null);
		
		if (cursor != null) { cursor.moveToFirst(); }
		
		return cursor;
	}
	
	public Cursor selectAll() throws SQLException {
		Cursor cursor = db.query(true, "words",new String[] {"_id", "word" , "url"},null,null,null,null,null,null);
		
		if (cursor !=null) {cursor.moveToFirst(); }
		
		return cursor;
	}
	public boolean update(long id, String word, String url) {
		ContentValues args = new ContentValues();
		args.put("word", word);
		args.put("url", url);
		
		return db.update("words", args, "_id"+ "=" + "id", null) > 0;
	}
}
